package com.example.demo.leetcode.top100;

import java.util.HashMap;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _8无重复字符的最长子串
 * @description
 * @date 2023/06/04 21:25
 * <p>
 * ******************************************************
 */
public class _8无重复字符的最长子串 {
    public int lengthOfLongestSubstring(String s) {
        // 记录字符对应的数量
        Map<Character, Integer> window = new HashMap<>();
        // 记录滑动窗口的左右位置
        int left = 0;
        int right = 0;
        int res = 0;
        while (right < s.length()) {
            char c = s.charAt(right);
            window.put(c, window.getOrDefault(c, 0) + 1);
            right++;

            // 窗口存在相同元素
            while (window.get(c) > 1) {
                char d = s.charAt(left);
                window.put(d, window.get(d) - 1);
                left++;
            }
            res = Math.max(res, right - left);
        }
        return res;
    }
}
